package jd.se.borrowrequest;

import jd.se.common.CurrentUser;
import jd.se.common.Result;
import jd.se.common.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;

@WebServlet({
        "/showBorrowRequest",
        "/confirmBorrowRequest",
        "/refuseBorrowRequest",
})
public class BorrowRequestAPI extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/showBorrowRequest".equals(path)) {
            CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);
            String lender_id = currentUser.getUserId();
            BorrowRequestService borrowRequestService = new BorrowRequestService();
            Map<String, Object> borrowRequestMap = borrowRequestService.getBorrowRequest(lender_id);
            Utils.outResult(resp, Result.success(borrowRequestMap));
        }
        if("/confirmBorrowRequest".equals(path)){
            String toId = request.getParameter("u_id");
            String bId = request.getParameter("b_id");
            BorrowRequestService borrowRequestService = new BorrowRequestService();
            Date borrow_date = new Date(System.currentTimeMillis());
            BInfo bInfo = new BInfo(toId,bId,borrow_date);
            borrowRequestService.confirmBorrowRequest(bInfo);
        }
        if("/refuseBorrowRequest".equals(path)){
            String toId = request.getParameter("u_id");
            String bId = request.getParameter("b_id");
            BorrowRequestService borrowRequestService = new BorrowRequestService();
            BInfo bInfo = new BInfo(toId,bId,null);
            borrowRequestService.refuseBorrowRequest(bInfo);
        }
    }
}
